import { createReducer } from './util';
import * as CompanyAction from '../actions/company';
import * as RunnableGroupAction from '../actions/runnable-group';
import _ from 'lodash';

export const currentUserCompanyList = createReducer(on => {
  on(CompanyAction.listByCurrentUser);
}, []);

export const searchCompanyList = createReducer(on => {
  on(CompanyAction.search);
}, { list: [], total: 0 });

export const companyAuthedDevTeamList = createReducer(on => {
  on(CompanyAction.listAuthedDevTeams);
  on(CompanyAction.unAuthTeam)
    .completed((state, action) => {
      return _.filter(state, (team) => team.id !== action.payload);
    });
}, []);

export const managedCompany = createReducer(on => {
  on(CompanyAction.managedCompany);
}, []);

const updateGroup = (groupList, groupId, updateObj) => {
  return groupList.map(group => {
    if (group.id !== groupId) {
      return group;
    }
    return Object.assign({}, group, updateObj);
  });
};

export const companyRunnableGroupList = createReducer(on => {
  on(CompanyAction.listRunnableGroups);
  on(RunnableGroupAction.assign)
    .completed((state, { groupId, teamId }) => updateGroup(state, groupId, { teamId }));
  on(RunnableGroupAction.updateMachines)
    .completed((state, { groupId, machineIds }) => updateGroup(state, groupId, { machineIds }));
}, []);

export const companyMachineList = createReducer(on => {
  on(CompanyAction.listMachines);
}, []);
